package com.bwda.dsrs.filecenter.quartz;

import com.bwda.dsrs.filecenter.domain.condition.tsktask.TskTaskCondition;
import com.bwda.dsrs.filecenter.domain.po.tsktask.TskTaskPo;
import com.bwda.dsrs.filecenter.domain.vo.tsktask.ScheduleJobVo;
import com.bwda.dsrs.filecenter.service.TskTaskService;
import com.bwda.dsrs.systemservice.domain.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * Description:任务加载器，系统启动时，加载数据库中状态为启用的所有任务
 *
 * @author liuxiaoyong
 * @date 2019/11/22
 */
@Component
public class JobLoader {
    private static Logger logger = LoggerFactory.getLogger(JobLoader.class);

    /**
     * Description: 加载数据库中状态为启用的所有任务
     */
    public void loadJobs() {
        TskTaskService taskService =  SpringUtil.getBean(TskTaskService.class);
        QuartzService quartzService = SpringUtil.getBean(QuartzService.class);

        TskTaskCondition condition = new TskTaskCondition();
        //查询状态为启用的任务
        condition. setTaskStatus(0);
        condition.setPageSize(1000);
        //读取数据库中状态为启用的所有任务
        List<TskTaskPo> poList = taskService.queryList(condition);
        logger.info("load task: {}", poList);

        for (TskTaskPo po : poList) {
            ScheduleJobVo job = new ScheduleJobVo();
            job.setJobId(po.getTaskId());
            job.setJobName(po.getTaskName());
            job.setJobGroup(po.getTaskGroup());
            job.setBeanClass(po.getExeClass());
            job.setCronExpression(po.getCronExpression());
            job.setDescription(po.getTaskDesc());

            //将每个task增加到执行列表中
            quartzService.addJob(job);
        }
    }

    /**
     * Description: 修改已加载到系统中的任务
     *
     * @param taskId 任务Id
     */
    public void reloadJob(Long taskId) {

        TskTaskService taskService = SpringUtil.getBean(TskTaskService.class);
        TskTaskPo po = taskService.query(taskId);

        logger.info("reload task: {}", po);

        ScheduleJobVo job = new ScheduleJobVo();
        job.setJobId(po.getTaskId());
        job.setJobName(po.getTaskName());
        job.setJobGroup(po.getTaskGroup());
        job.setBeanClass(po.getExeClass());
        job.setCronExpression(po.getCronExpression());
        job.setDescription(po.getTaskDesc());

        QuartzService quartzService = SpringUtil.getBean(QuartzService.class);

        if (po.getTaskStatus().equals(1)) {
            //状态为停用，则删除已加载的任务
            quartzService.deleteJob(job);
        } else if (po.getTaskStatus().equals(0) ) {
            //状态为启用，则再重新加载任务
            quartzService.addJob(job);
        }
    }
}
